"""获取48小时内的核酸检测结果"""
import time

import pyautogui
import os
import easyocr
import requests

IMAGE_FOLDER = "img"
IMAGE_NAMES = os.listdir(IMAGE_FOLDER)
IMAGE_PATHS = [os.path.join(IMAGE_FOLDER, n) for n in IMAGE_NAMES]

HEIGHT = 50


def locate(image_path):
    location = pyautogui.locateOnScreen(image_path)
    if location is not None:
        center = pyautogui.center(location)
        return center
    else:
        return None


def get_time():
    # 连续点击操作
    for i, image_path in enumerate(IMAGE_PATHS[0:4]):
        c = locate(image_path)
        if c is None:
            raise ValueError(f"{image_path} not found!")
        pyautogui.click(c[0], c[1])
        if i == 0:
            time.sleep(0.8)
        elif i == 1:
            time.sleep(2)
        elif i == 2:
            time.sleep(1)
            pyautogui.scroll(-50)
            time.sleep(1)
    # 查找阴性证明
    time.sleep(0.8)
    c = locate(IMAGE_PATHS[5])
    if c is None:
        return None
    else:
        left, top, width, height = pyautogui.locateOnScreen(IMAGE_PATHS[4])
        time_image = pyautogui.screenshot(region=(left, top + height, width, HEIGHT))
        time_image_path = os.path.join(IMAGE_FOLDER, "temp.png")
        time_image.save(time_image_path)
        reader = easyocr.Reader(['ch_sim'], gpu=False)  # need to run only once to load model into memory
        result = reader.readtext(time_image_path, detail=0)[0]
        # 后处理
        if len(result) == len("2022-01-0711:11:21"):
            result = result[:10] + ' ' + result[10:15]
        # 标点符号强转
        result = list(result)
        result[4], result[7] = '-', '-'
        result[13] = ':'
        result = "".join(result)
        return result


def get_time_by_request():
    url = "https://data.xa.gov.cn"
    re = requests.get(url)
    with open("爬取内容.txt", "w", encoding="utf-8") as f:
        f.write(re.text)
    print(re.text)


if __name__ == '__main__':
    print(get_time())
